package com.spyx.common.service;


import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //定义发送消息的方法
    //mq发送消息的三要素: 交换机,路由key,消息内容
    public boolean sendMessage(String exchange,String routingKey,Object message){
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
        return true;
    }

    //发送延迟消息
    //delayTime延迟时间
    public boolean sendDelayMessage(String exchange,String routingKey,Object message,int delayTime){
        rabbitTemplate.convertAndSend(exchange, routingKey, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message mess) throws AmqpException {
                mess.getMessageProperties().setDelay(delayTime*1000);//设置消息的延迟时间
                return mess;
            }
        });
        return true;
    }

}
